package scsys.webServlet.main;

import com.alibaba.fastjson.JSON;
import scsys.pojo.Course;
import scsys.pojo.Elective;
import scsys.pojo.userCourse;
import scsys.servlet.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/select_class_Servlet")
public class select_class_Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CourseService courseService = new CourseServiceImpl();
        EletiveService eletiveService = new EletiveServiceImpl();

        //1. 接收数据
        BufferedReader br = request.getReader();
        String params = br.readLine();//json字符串
        //转为userCourse对象
        userCourse userCourse = JSON.parseObject(params, userCourse.class);
        // 判断选择课程是否存在
        Course course = new Course();
        course.setId(userCourse.getCourseId());
        course = courseService.selectOne(course);
        // 是否已选
        Elective sele_elective = new Elective();
        sele_elective.setUserName(userCourse.getUserName());
        sele_elective.setCourseId(userCourse.getCourseId());
        sele_elective = eletiveService.selectOne(sele_elective);
        if((course.getId()!="") && (sele_elective == null)){
            // 存在该课程 开始选课
            Elective elective = new Elective();
            elective.setUserName(userCourse.getUserName());
            elective.setCourseId(userCourse.getCourseId());
//            try {
                eletiveService.add(elective);
                response.getWriter().write("yes");
//            } catch (Exception e) {
//                response.getWriter().write("no");
//                e.printStackTrace();
//            }
        }else {
            // 不存在该课程 选课失败
            response.getWriter().write("no");
        }
        userCourse = null;
        course = null;
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
